package SparkStreaming

import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
import org.apache.spark.streaming.{Seconds, StreamingContext}

object Consumer {
  def main(args: Array[String]): Unit = {
    // 1. 配置 Spark Streaming
    val conf = new SparkConf().setMaster("local[*]").setAppName("KafkaConsumer")
    val ssc = new StreamingContext(conf, Seconds(5))
    ssc.sparkContext.setLogLevel("ERROR")

    // 2. 配置 Kafka 消费者参数
    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "192.168.23.128:9092", // 替换为你的 Kafka Broker 地址
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "spark-consumer-group",
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )
    val topics = Array("attendance") // 需要消费的 Kafka 主题

    // 3. 创建 Kafka 数据流
    val kafkaStream = KafkaUtils.createDirectStream[String, String](
      ssc,
      LocationStrategies.PreferConsistent,
      ConsumerStrategies.Subscribe[String, String](topics, kafkaParams)
    )

    // 4. 处理 Kafka 消息
    val records = kafkaStream.map(record => record.value())
    records.foreachRDD(rdd => {
      if (!rdd.isEmpty()) {
        println("接收到的数据：")
        rdd.collect().foreach(println)
      }
    })

    // 5. 启动 StreamingContext
    ssc.start()
    ssc.awaitTermination()
  }
}
